import datetime
from haystack.indexes import *
from haystack import site
from goodies.models import Book

from sorl.thumbnail import get_thumbnail

class BookIndex(SearchIndex):
    text          =  CharField(document=True, use_template=True)

    author        =  CharField(model_attr='author',null=True,faceted=True)

    name          =  CharField(model_attr='name'  ,null=True)
    year          =  IntegerField(null=True)
    price         =  IntegerField(null=True)
    description   =  CharField(model_attr='description',null=True)

    author_auto   =  NgramField(model_attr='author', null=True)
    name_auto     =  NgramField(model_attr='name',   null=True)

    categories    = MultiValueField(null=True)
    thumbnail_url = CharField(null=True)



#    categories = MultiValueField() 
    def prepare_name(self,obj):
        if not obj.name:
            return 'blablabla'
        return obj.name

    def prepare_categories(self, obj):
        if obj.categories and obj.categories.all(): 
            return [i.pk for i in obj.categories.all()]
        return None

    def prepare_thumbnail_url(self,obj):
        if  obj.pictures and obj.pictures.all():
            return get_thumbnail(obj.pictures.all()[0].image, '100x100', crop='center').url

    def prepare_year(self,obj):
        try:    return int(obj.year)
        except: return 0
    def prepare_price(self,obj):
        try:    return int(obj.price)
        except: return 0

        

 #   date   =  DateTimeField(model_attr='date')



    def get_model(self):
        return Book

    def index_queryset(self, using=None):
        """Used when the entire index for model is updated."""
        return self.get_model().objects.all()#filter(date__lte=datetime.datetime.now())

site.register(Book, BookIndex)
